const getProxyApi = require('./devProxy');
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
// const PreloadWebpackPlugin = require('@vue/preload-webpack-plugin');
const productionGzipExtensions = ['js', 'css'];
const path = require('path');
function resolve(dir) {
  return path.join(__dirname, dir);
}
const port = 4200; // dev port

module.exports = {
  publicPath: process.env.VUE_APP_FRONT_PREFIX,
  parallel: false,
  devServer: {
    client: {
      overlay: false
    },
    port: port,
    headers: {
      // "Access-Control-Allow-Origin": "*",
      // 本地代理请求允许携带cookie; 若开启网关，则不需配置，因为网关已配置了允许跨域+携带cookie访问
      'Access-Control-Allow-Credentials': 'true'
    },
    proxy: getProxyApi()
  },
  productionSourceMap: process.env.NODE_ENV !== 'production',
  css: {
    loaderOptions: {
      scss: {
        // additionalData: `@import "~@/assets/css/index.scss";` // v10后： prependData => additionalData
        additionalData: (content, loaderContext) => {
          // 升级dart-sass后写法
          const { resourcePath } = loaderContext;
          if (resourcePath.endsWith('index.scss')) return content;
          // prepend import sentence
          return `@import "~@/assets/css/index.scss";
          ${content}`;
        }
      }
    }
  },
  // 自定义webpack配置
  configureWebpack: {
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    plugins: [
      // new PreloadWebpackPlugin(),
      new CompressionWebpackPlugin({
        algorithm: 'gzip',
        test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
        threshold: 10240,
        minRatio: 0.8
      }),
      new NodePolyfillPlugin()
    ]
  },
  // 默认情况下 babel-loader 会忽略所有 node_modules 中的文件。如果你想要通过 Babel 显式转译一个依赖，可以在这个选项中列出来。
  transpileDependencies: [],
  chainWebpack: config => {
    config.module
      .rule('compile')
      .test(/\.js$/)
      .include.add(resolve('src'))
      // .add(resolve("node_modules/element-ui"))
      .end()
      .use('babel')
      .loader('babel-loader');
    // set svg-sprite-loader
    config.module.rule('svg').exclude.add(resolve('src/assets/icons')).end();
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end();
    config.when(process.env.NODE_ENV !== 'development', config => {
      // config
      //   .plugin('ScriptExtHtmlWebpackPlugin') // 与PreloadWebpackPlugin冲突！！！！！！！！！
      //   .after('html')
      //   .use('script-ext-html-webpack-plugin', [
      //     {
      //       // `runtime` must same as runtimeChunk name. default is `runtime`
      //       inline: /runtime\..*\.js$/
      //     }
      //   ])
      //   .end()
      config.optimization.splitChunks({
        chunks: 'all',
        cacheGroups: {
          libs: {
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial' // only package third parties that are initially dependent
          },
          elementUI: {
            name: 'chunk-elementUI', // split elementUI into a single package
            test: /[\\/]node_modules[\\/]_?element-plus(.*)/, // in order to adapt to cnpm
            priority: 20 // the weight needs to be larger than libs and app or it will be packaged into libs or app
          },
          commons: {
            name: 'chunk-commons',
            test: resolve('src/components'), // can customize your rules
            minChunks: 3, //  minimum common number
            priority: 5,
            reuseExistingChunk: true
          }
        }
      });
      config.optimization.runtimeChunk('single');
    });
  }
};
